import { EllipsisOutlined, PlusOutlined } from "@ant-design/icons";
import {
  ActionType,
  ModalForm,
  ProColumns,
  ProForm,
  ProFormDatePicker,
  ProFormDateRangePicker,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
} from "@ant-design/pro-components";
import { ProTable, TableDropdown } from "@ant-design/pro-components";
import { Button, message, Upload, UploadProps } from "antd";
import { useEffect, useRef } from "react";
import request from "umi-request";
import axios from "../../../../utils/axios";

type GithubIssueItem = {
  materialStyleId: number;
  materialStyleName: string;
  materialsCode: string;
  materialsDrawing: string;
  materialsId: number;
  materialsName: string;
  materialsStyle: string;
  msConsumableMaterial: number;
  msConsumableMaterialEndTime: string;
  msConsumableMaterialStartTime: string;
  msConsumptionQuantity: string;
  msId: number;
  msState: number;
  msUpdateLastTime: string;
  supAbbreviations: string;
  supId: number;
  supName: string;
  supNumber: number;
  userId: number;
  userName: string;
};

const columns: ProColumns<GithubIssueItem>[] = [
  {
    title: "序号",
    dataIndex: "msId",
    key: "msId",
    valueType: "indexBorder",
    width: 48,
  },
  {
    title: "供方代码",
    key: "supNumber",
    dataIndex: "supNumber",
    filters: true,
    onFilter: true,
    copyable: true,
    ellipsis: true,
  },
  {
    disable: true,
    key: "supAbbreviations",
    title: "供方名称",
    dataIndex: "supAbbreviations",
    filters: true,
    onFilter: true,
  },
  {
    disable: true,
    title: "物料代码",
    dataIndex: "materialsCode",
    key: "materialsCode",
    filters: true,
    onFilter: true,
  },
  {
    disable: true,
    title: "物料名称",
    key: "materialsName",
    dataIndex: "materialsName",
    filters: true,
    onFilter: true,
  },
  {
    title: "图号",
    key: "materialsDrawing",
    dataIndex: "materialsDrawing",
    width: 48,
    search: false,
  },
  {
    key: "materialsStyle",
    title: "规格型号",
    dataIndex: "materialsStyle",
    width: 48,
    search: false,
  },
  {
    title: "是否消耗物料",
    dataIndex: "materialStyleId",
    key: "materialStyleId",
    width: 48,
    search: false,
  },
  {
    title: "消耗物料类型",
    dataIndex: "materialStyleName",
    key: "materialStyleName",
    width: 48,
    search: false,
  },
  {
    title: "消耗数量",
    dataIndex: "msConsumableMaterial",
    key: "msConsumableMaterial",
    width: 48,
    search: false,
  },
  {
    title: "消耗开始时间",
    key: "msConsumptionQuantity",
    dataIndex: "msConsumptionQuantity",
    valueType: "dateTime",
    sorter: true,
    hideInSearch: true,
  },
  {
    title: "消耗结束时间",
    key: "msConsumableMaterialStartTime",
    dataIndex: "msConsumableMaterialStartTime",
    valueType: "dateTime",
    sorter: true,
    hideInSearch: true,
  },
  {
    title: "更新时间",
    key: "msUpdateLastTime",
    dataIndex: "msUpdateLastTime",
    valueType: "dateTime",
    sorter: true,
    hideInSearch: true,
  },
  {
    title: "维护人",
    dataIndex: "userName",
    key: "userName",
    width: 48,
    search: false,
  },
  {
    title: "操作",
    valueType: "option",
    key: "option",
    render: (text, record, _, action) => [
      <a
        key="editable"
        onClick={() => {
          action?.startEditable?.(record.msId);
        }}
      >
        编辑
      </a>,
      <a
        onClick={() => {
          action?.startEditable?.(record.msId);
        }}
        key="msId"
      >
        删除
      </a>,
    ],
  },
];

export default () => {
  // useEffect(()=> {

  // },[])
  const actionRef = useRef<ActionType>();
  return (
    <ProTable<GithubIssueItem>
      rowKey={(record) => record.msId}
      columns={columns}
      actionRef={actionRef}
      cardBordered
      /* ---------------查询表格--------------- */
      request={async (params = {}, sort, filter) => {
        console.log(params);
        let x0 = "",
          x1 = "",
          x2 = "",
          x3 = "";
        if (params.supNumber != undefined) {
          x0 = params.supNumber;
        }
        if (params.supAbbreviations != undefined) {
          x1 = params.supAbbreviations;
        }
        if (params.materialsCode != undefined) {
          x2 = params.materialsCode;
        }
        if (params.materialsName != undefined) {
          x3 = params.materialsName;
        }

        let data = await request(
          `/material/selectMaterialSupplier?supNumber=${x0}&supAbbreviations=${x1}&materialsCode=${x2}&materialsName=${x3}`
        );
        data = data.data.listMaterialSupplier;
        console.log(data);

        return { data, success: true };
      }}
      /* -------------------表格的修改+ 删除+保存---------------------  */
      editable={{
        type: "multiple",
        /* 保存修改的数据 */
        onSave: async (key, row, originRow): Promise<any> => {
          console.log(key, row, originRow);
          try {
            const data = await axios({
              url: "/api3/material/updateMaterialSupplier",
              data: row,
              method: "post",
            });
            return console.log(data);
          } catch (err) {
            return console.log(err);
          }
        },
        /* 删除数据 */
        onDelete: async (key, row): Promise<any> => {
          console.log(key, row);
          try {
            const data = await axios({
              url: `/api3/material/deleteTestingEquipment`,
              params: key,
              method: "post",
            });
            return console.log(data);
          } catch (err) {
            return console.log(err);
          }
        },
      }}
      columnsState={{
        persistenceKey: "pro-table-singe-demos",
        persistenceType: "localStorage",
      }}
      search={{
        labelWidth: "auto",
      }}
      form={{
        // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === "get") {
            return {
              ...values,
              created_at: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      pagination={{
        pageSize: 5,
        onChange: (page) => console.log(page),
      }}
      dateFormatter="string"
      toolBarRender={() => [
        <div>
          <ModalForm<{
            name: string;
            company: string;
          }>
            title="新建表单"
            trigger={
              <Button type="primary">
                <PlusOutlined />
                新增
              </Button>
            }
            autoFocusFirstInput
            modalProps={{
              onCancel: () => console.log("run"),
            }}
            submitTimeout={2000}
            /* 新增表格 */
            onFinish={async (values) => {
              console.log(values);
              axios({
                url: "/api3/material/addMaterialSupplier",
                data: { ...values },
                method: "post",
              })
                .then((data) => console.log(data))
                .catch((error) => console.log(error));
              message.success("提交成功");
              return true;
            }}
          >
            <ProForm.Group>

              <ProFormText
                width="md"
                name="materialStyleName"
                label="物料名称"
                placeholder="请输入名称"
              />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormText
                width="md"
                name="supNumber"
                label="供方代号"
                placeholder="请输入名称"
              />
              <ProFormText
                width="md"
                name="supAbbreviations"
                label="供方名称"
                placeholder="请输入名称"
              />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormText
                width="md"
                name="materialsStyle"
                label="规格型号"
                placeholder="请输入名称"
              />
              <ProFormText
                width="md"
                name="materialsDrawing"
                label="图号"
                placeholder="请输入名称"
              />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormRadio.Group
                name="msConsumableMaterial "
                label="消耗物料"
                options={[
                  {
                    label: "是",
                    value: "0",
                  },
                  {
                    label: "否",
                    value: "1",
                  },
                ]}
              />
            </ProForm.Group>
            <ProForm.Group >
              <ProFormSelect
                width={150}
                fieldProps={{
                  labelInValue: true,
                }}
                request={async () => {
                  console.log('第二个')
                  let data = await axios({
                    url: "/api3/material/selectMaterialStyle",
                  });
                  let c = [...data.data.data];
                  let a: { label: string; value: number };
                  if (data.data.code === 200) {
                    let arr = [];
                    for (let i = 0; i < c.length; i++) {
                      a = {
                        label: c[i].materialStyleName,
                        value: c[i].materialStyleId,
                      };
                      arr.push(a);
                    }
                    return arr;
                  } else {
                    return [];
                  }
                }}
                name="materialsName"
                label="消耗物料类型"
              />
              <ProFormText
                width="md"
                name="msConsumableMaterial"
                label="消耗数量"
                placeholder="消耗数量"
              />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormDatePicker
                name="msConsumableMaterialStartTime"
                width="md"
                label="消耗物料开始时间"
              />
              <ProFormDatePicker
                name="msConsumableMaterialEndTime"
                width="md"
                label="消耗物料结束时间"
              />
            </ProForm.Group>
          </ModalForm>
        </div>,
        <div>
          <Button>
            <a href="/api3/material/derivedMaterialSupplierExcel">批量导出</a>
          </Button>
          <Button>
            <a href="/api3/material/materialSupplierTemplateDownload">
              模板下载
            </a>
          </Button>
          <Upload {...props} style={{ float: "left" }}>
            <Button>批量导入</Button>
          </Upload>
        </div>,
      ]}
    />
  );
};
/* 批量导入 */
const props: UploadProps = {
  name: "uploadFile",
  action: "/api3/material/addMaterialSupplierSExcel",
  headers: {
    authorization: "authorization-text",
  },
  method: "post",
  onChange(info) {
    console.log(info);
    if (info.file.status !== "uploading") {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === "done") {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === "error") {
      message.error(`${info.file.name} 上传失败`);
    }
  },
};
